const Excel = require('exceljs')
const axios = require('axios')

// 导出站点巡检记录为Excel文件
function exportType0(inspect) {
    const wb = new Excel.Workbook()
    var bigList = []
    inspect.cates = JSON.parse(inspect.catesJson)
    delete inspect.catesJson
    const submitPersonName = inspect["submitPersonName"]
    const stationName = inspect['stationName']
    const submitTime = inspect['submitTime']
    const weatherInfo = inspect['weatherInfo'] || '多云'
    var ws = null
    //第1行
    ws = wb.addWorksheet(submitPersonName)
    ws.addRow(['环保设施日常巡检记录'])
    ws.getCell('A1').font = {
        name: 'SimSun',
        bold: true,
        size: 13
    } //最顶部标题： 宋体 20
    ws.mergeCells('A1:I1')

    //第2行
    ws.addRow(['设施名称', stationName, 'c', 'd', 'e', '日期', submitTime, '天气状况', weatherInfo])
    ws.mergeCells('B2:E2')

    //第3行
    ws.addRow(['维护管理单位', '惠州大隆基环境治理有限公司'])
    ws.mergeCells('B3:I3')

    //第4行
    ws.addRow(['主要巡检事项'])
    ws.mergeCells('A4:I4')
    const row4 = ws.getRow(4)
    row4.hidden = true

    //第5行
    ws.addRow(['类别', '序号', '项目', '', '运行情况', '图1', '图2', '图3', '备注'])
    ws.mergeCells('C5:D5')

    var strangeIndex = 0
    for (var i = 0; i < inspect.cates.length; i++) {
        let cate = inspect.cates[i]
        let children = cate.children || []
        for (var idx = 0; idx < children.length; idx++) {
            let child = children[idx]
            let child_goal = child.goal
            let child_text = child.text
            let child_check = child.checkFlag
            let child_check_str = '正常'
            if (child_check == 1) {
                child_check_str = '异常'
            } else if (child_check == 2) {
                child_check_str = '运行正常'
            }
            strangeIndex = strangeIndex + 1
            for (var index = 0; index < 2; index++) {
                const A_str = cate.text
                const B_str = strangeIndex.toString()
                const C_str = index == 0 ? "项目" : "目的"
                const D_str = index == 0 ? child_text : child_goal
                const E_str = child_check_str
                ws.addRow([A_str, B_str, C_str, D_str, E_str])
                if (E_str == '异常') {
                    ws.getCell('E' + ws.lastRow.number.toString()).fill = {
                        type: 'pattern',
                        pattern: 'solid',
                        fgColor: {
                            argb: 'ffff0000'
                        },
                    }
                }
            }
            let last_num = ws.lastRow.number
            let lastlast_num = (last_num - 1)
            ws.mergeCells("B" + lastlast_num.toString() + ":B" + last_num.toString())
            ws.mergeCells("E" + lastlast_num.toString() + ":E" + last_num.toString())
        }
        let p_last_num = ws.lastRow.number
        let p_lastlast_num = (p_last_num - children.length * 2 + 1)
        ws.mergeCells("A" + p_lastlast_num.toString() + ":A" + p_last_num.toString())
    }

    //统一居中对齐
    for (var i = 1; i <= ws.rowCount; i++) {
        let row = ws.getRow(i)
        row.height = 20 //统一行高
        row.alignment = {
            horizontal: 'center',
            vertical: 'middle'
        }
        if (i > 1) {
            row.font = {
                name: 'SimSun',
                size: 8,
            }

        }
    }

    ws.getCell('G2').font = {
        name: 'SimSun',
        size: 7
    }

    ws.pageSetup.margins = {
        left: 0.4,
        right: 0.4,
        top: 0.3,
        bottom: 0.3,
        header: 0.1,
        footer: 0.1
    }

    //列宽
    ws.properties.defaultColWidth = 11
    ws.getColumn('B').width = 6
    ws.getColumn('C').width = 6
    ws.getColumn('D').width = 22
    ws.getColumn('E').width = 9
    let end_num = ws.lastRow.number
    for (var i = 6; i <= end_num; i++) {
        ws.getCell('D' + i).alignment = {
            horizontal: 'left',
            vertical: 'middle',
            wrapText: true
        }
        ws.getCell('A' + i).alignment = {
            horizontal: 'center',
            vertical: 'middle',
            wrapText: true
        }
    }

    //边框
    const abcdefghi = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
    for (var i = 1; i <= end_num; i++) {
        for (const str of abcdefghi) {
            ws.getCell(str + i).border = {
                top: {
                    style: 'thin'
                },

                left: {
                    style: 'thin'
                },
                bottom: {
                    style: 'thin'
                },
                right: {
                    style: 'thin'
                }
            }
        }
    }

    var rowIndex = 6
    for (var i = 0; i < inspect.cates.length; i++) {
        let cate = inspect.cates[i]
        const children = cate.children || []
        for (var idx = 0; idx < children.length; idx++) {
            let child = children[idx]
            let pics = child.pictures || []
            let types = child.types || []
            let note = child.note || ''
            for (var index_double = 0; index_double < 2; index_double++) {
                if (index_double == 0) { //如果rowIndex为奇数
                    if (types.length > 0) {
                        handleWtypes(ws, types, rowIndex)
                    } else {
                        const efg = ['F', 'G', 'H']
                        for (var index = 0; index < efg.length; index++) { //图片最多三张
                            bigList.push(handleImgsCells(wb, ws, efg[index], pics, types, index,
                                rowIndex))
                        }
                    }
                    handleNotes(note, ws, rowIndex)
                }
                rowIndex = rowIndex + 1
            }
        }
    }
    return Promise.all(bigList).then(res => {
        bigList = [];
        return wb.xlsx.writeBuffer().then(buffer => {
            const fileName = `${stationName} ${submitTime} ${submitPersonName}.xlsx`;
            const dayjs = require('dayjs');
            const date = dayjs(`${submitTime}`).format('YYYY-MM-DD');
            const savePath = `/data_s001/data/udata/real/13924290420/大隆基/站点巡检/${date}/${fileName}`;
            const fs = require('fs');
            const path = require('path');
            const dirPath = path.dirname(savePath);
            if (!fs.existsSync(dirPath)) {
                fs.mkdirSync(dirPath, { recursive: true });
            }
            // 使用异步写入替代同步写入
            return new Promise((resolve, reject) => {
                fs.writeFile(savePath, buffer, (err) => {
                    if (err) {
                        console.error(`[${new Date().toLocaleString()}] Excel文件保存失败: ${err.message}`);
                        reject(err);
                        return;
                    }
                    resolve(savePath);
                });
            });
        });
    }).catch(err => {
        console.error(`[${new Date().toLocaleString()}] 处理Excel过程中出错:`, err);
        throw err;
    });
}

function handleNotes(note, ws, rowIndex) {
    let cell_begin = 'I' + rowIndex.toString()
    let cell_end = 'I' + (rowIndex + 1).toString()
    let targetCells = cell_begin + ":" + cell_end
    if (note.length > 0) {
        let theCell = ws.getCell(cell_begin)
        theCell.value = note
        theCell.alignment = {
            horizontal: 'left',
            vertical: 'middle',
            wrapText: true
        }
    }
    ws.mergeCells(targetCells)
}

async function handleImgsCells(wb, ws, co, pics, types, index, rowIndex) {
    let cell_begin = co + rowIndex.toString()
    let cell_end = co + (rowIndex + 1).toString()
    let targetCells = cell_begin + ":" + cell_end
    let fileID = pics[index]
    let wtype = types[index]
    if (fileID != null) {
        ws.mergeCells(targetCells)
        return new Promise((resolve, reject) => {
            axios({
                url: fileID,
                method: 'get',
                responseType: 'arraybuffer',
                headers: {
                    "content-type": "application/octet-stream"
                },
            }).then(response => {
                const imageId = wb.addImage({
                    buffer: response.data,
                    extension: 'jpg'
                })
                ws.addImage(imageId, targetCells)
                resolve(true)
            }).catch(error => {
                console.error(`[${new Date().toLocaleString()}] 获取图片失败:`, error);
                reject(error);
            })
        })
    } else if (wtype != null) {
        return new Promise((resolve, reject) => {
            resolve(true)
        })
    } else {
        ws.mergeCells(targetCells)
        return new Promise((resolve, reject) => {
            resolve(true)
        })
    }
}

function handleWtypes(ws, types, rowIndex) {
    for (var index = 0; index < 6; index++) {
        if (index == 0) {
            handleWtypesCells(ws, 'F', types, index, rowIndex)
        } else if (index == 1) {
            handleWtypesCells(ws, 'F', types, index, rowIndex + 1)
        } else if (index == 2) {
            handleWtypesCells(ws, 'G', types, index, rowIndex)
        } else if (index == 3) {
            handleWtypesCells(ws, 'G', types, index, rowIndex + 1)
        } else if (index == 4) {
            handleWtypesCells(ws, 'H', types, index, rowIndex)
        } else if (index == 5) {
            handleWtypesCells(ws, 'H', types, index, rowIndex + 1)
        }
    }
}

function handleWtypesCells(ws, co, types, index, rowIndex) {
    let cell = co + rowIndex.toString()
    let wtype = types[index]
    if (wtype != null) {
        let unit = wtype.unit || ""
        let value = wtype.value || "0"
        let theCell = ws.getCell(cell)
        theCell.value = wtype.text + "：" + value + " " + unit
        theCell.alignment = {
            horizontal: 'left',
            vertical: 'middle'
        }
    }
}

module.exports = {
    exportType0
}